package org.example.message_queue.mqserver;

import org.example.message_queue.common.*;
import org.example.message_queue.mqserver.core.BasicProperties;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BrokerServer {
    private ServerSocket serverSocket = null;
    private VirtualHost virtualHost = new VirtualHost("default");
//    管理当前所有对话
//    key：channelId     value：对应的会话对象
    private ConcurrentHashMap<String,Socket> sessions = new ConcurrentHashMap<String,Socket>();
//    引入线程池处理多个客户端请求
    private ExecutorService executorService = null;
//    引入boolean变量控制服务器是否继续运行
    private boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

//    开启服务器
    public void start() throws IOException {
        System.out.println("[BrokerServer]启动！");
        executorService = Executors.newCachedThreadPool();
        try{
            while (runnable){
                Socket clientSocket = serverSocket.accept();
                executorService.submit(()->{
                    processConnection(clientSocket);
                });
            }
        }catch (SocketException e){
            System.out.println("[BrokerSerer] 服务器停止运行！");
        }
    }

//    关闭服务器
    public void stop() throws IOException {
        runnable = false;
        executorService.shutdownNow();
        serverSocket.close();
    }

    private void processConnection(Socket clientSocket) {
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            try(DataInputStream dataInputStream = new DataInputStream(inputStream);
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream)){
                while (true){
//                    1.读取请求并响应
                    Request request = readRequest(dataInputStream);
//                    2.根据请求计算响应
                    Response response = process(request,clientSocket);
//                    3.把响应写回给客户端
                    writeResponse(dataOutputStream,response);
                }
            }
        } catch (EOFException | SocketException e){
            System.out.println("[BrokerServer] 连接关闭 客户端的地址："+clientSocket.getInetAddress().toString()+":"+clientSocket.getPort());
        } catch (IOException | ClassNotFoundException | MqException e) {
            System.out.println("[BrokerServer] connection 出现异常！");
            e.printStackTrace();
        }finally {
            try {
//                当所有连接都处理完，要记得关闭socket
                clientSocket.close();
//                一个TCP连接中，可能包含多个channel，需要将当前session对应的所有的channel都处理掉
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()){
            throw new IOException("读取请求格式出错！");
        }
        request.setPayload(payload);
        return request;
    }

    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
//        1.将request中的payload进行解析
//        反序列化
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[Reqest] rid="+basicArguments.getChannelId()+", channleId="+basicArguments.getChannelId());
        boolean ok = true;
//        2.根据type的值，方便出下一步要做什么
        if (request.getType() == 0x1){
//            创建channel
            sessions.put(basicArguments.getChannelId(),clientSocket);
            System.out.println("[Request] 创建channel成功！channelId="+basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[Request] 销毁channel成功！channelId="+basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
//            创建交换机
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments)basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(),arguments.getExchangeType(),arguments.isDurable(),arguments.isAutoDelete(),arguments.getArguments());
        } else if (request.getType() == 0x4) {
//            删除交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments)basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
//            创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments)basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(),arguments.isDurable(),arguments.isAutoDelete(),arguments.isExclusive(),arguments.getArguments());
        } else if (request.getType() == 0x6) {
//            删除队列
            QueueDeleteArguments arguments = (QueueDeleteArguments)basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
//            创建绑定
            QueueBindArguments arguments = (QueueBindArguments)basicArguments;
            ok = virtualHost.queueBind(arguments.getExchangeName(), arguments.getQueueName(), arguments.getBinding());
        } else if (request.getType() == 0x8) {
            QueueUnbindArguments arguments = (QueueUnbindArguments)basicArguments;
            ok = virtualHost.queueUnbind(arguments.getExchangeName(), arguments.getQueueName());
        }else if (request.getType() == 0x9){
            BasicPublishArguments arguments = (BasicPublishArguments)basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(), arguments.getBasicProperties(), arguments.getBody());
        }else if (request.getType() == 0xa){
//            订阅消息
            BasicConsumeArguments arguments = (BasicConsumeArguments)basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(), new Consumer() {
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
//                    1.根据channelId找到socket对象
                    Socket clientSocket = sessions.get(consumerTag);
                    if (clientSocket == null || clientSocket.isClosed()){
                        throw new MqException("[BrokerServe] 订阅消息的客户端已经关闭！");
                    }
//                    2.构造响应数据
                    SubScribeReturns subScribeReturns = new SubScribeReturns();
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setRid("");
                    subScribeReturns.setOk(true);
                    subScribeReturns.setConsumerTag(consumerTag);
                    subScribeReturns.setBasicProperties(basicProperties);
                    subScribeReturns.setBody(body);

                    byte[] payload = BinaryTool.toBytes(subScribeReturns);
                    Response response = new Response();
                    response.setType(0xc);
                    response.setLength(payload.length);
                    response.setPayload(payload);
//                    3.将数据写回客户端
                    DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                    writeResponse(dataOutputStream,response);
                }
            });
        } else if (request.getType() == 0xb) {
//            调用basicAck确认信息
            BasicAckArguments arguments = (BasicAckArguments)basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        }else {
//            当前请求非法
            throw new MqException("[BrokerServer] 未知的类型！type="+request.getType());
        }
//        3.构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);

        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(response.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response]rid="+basicReturns.getRid()+", channelId="+basicReturns.getChannelId()+", type="+response.getType()+", length="+response.getLength());
        return response;
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
//        刷新缓冲区
        dataOutputStream.flush();
    }

    private void clearClosedSession(Socket clientSocket) {
//        遍历sessions的哈希表，把该被关闭的socket对应的键值对都删掉
        List<String> toDeleteChannelId = new LinkedList();
        for (Map.Entry<String,Socket> entry : sessions.entrySet()){
            if (entry.getValue() == clientSocket){
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId){
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer]清理 session完成！被清理的channelId="+toDeleteChannelId);
    }
}
